import Vue from 'vue';
import Vuex from 'vuex';
import {setSessionStorageItem, getSessionStorageItem, arrayToJson} from 'components/api/utils';
import {getUserInfoByUserId, getUsercardList} from 'components/api/interface-hhy';
import {getBusinessSetting} from 'components/api/interface-saas';
import {MessageBox} from 'mint-ui';
Vue.use(Vuex);
export default new Vuex.Store({
  state: {
    totalPrice: 0,
    foodsInCart: [],
    orderNote: '',
    // userInfo: {},
    allCardsList: [],
    reduceCost: 0,
    // pointsConfig: {},
    sortIndex: 0,
    localFoodsInCart: [],
    businessSettingInfo: {},
    selectedCard: {},
    dishesMakeMethod: [],
    _tempFoodsInCart: [],
    _tempFoodCount: 0,
    _inertFoodCount: 0,
    userTel: '',
    userCaptcha: '',
    arriveTime: 0,    // 配送详情-送达时间
    personNum: 0,    // 配送详情-人数
    goodsCartShow: false, // 控制手机返回键
    foodDetailShow: false // 食品详情
  },
  // 添加的商品元素
  addCartEl: {},
  mutations: {
    setGoodsCartShow(state, value) {
      state.goodsCartShow = value;
    },
    setFoodDetailShow(state, value) {
      state.foodDetailShow = value;
    },
    increment(state) {
      state.count++
    },
    setOrderNote: function (state, allNote) {
      state.orderNote = allNote;
    },
    setUserTel: function (state, tel) {
      state.userTel = tel;
    },
    setUserCaptcha: function (state, captcha) {
      state.captcha = captcha;
    },
    // 将商品加入购物车
    addFoodsToCart: function (state, food) {
      // 加入购物车 （无菜品要求）
      let temp = state.foodsInCart.findIndex((item) => { // 查找匹配的商品
        return item.name === food.name && item.id === food.id && item.specId === food.specId && item.optionList === food.optionList;
      });
      if (temp === -1) {
        if (!food.count) {
          Vue.set(food, 'count', 1); // 该食品是否有count属性，没有就添加并初始化为1;
        }
        state.foodsInCart.push(food);
        if (!food.sort) {
          Vue.set(food, 'sort', state.stateIndex + 1);
        }
      } else {
        state.foodsInCart[temp].count += 1;
      }
    },
    // 从购物车中移除商品
    removeFoodsFromCart: function (state, food) {
      let temp = state.foodsInCart.findIndex((item) => { // 查找匹配的商品
        return item.name === food.name && item.id === food.id && item.specId === food.specId && item.optionList === food.optionList;
      });
      if (temp !== -1) {
        let currentFood = state.foodsInCart[temp];
        // TODO 优化判断条件
        if (currentFood.count > 0) {
          currentFood.count -= 1;
          if (currentFood.count === 0) {
            state.foodsInCart.splice(temp, 1);
          }
        } else {
          state.foodsInCart.splice(temp, 1);
        }
      }
      setSessionStorageItem('foodsInCart', state.foodsInCart);
      state.localFoodsInCart = getSessionStorageItem('foodsInCart');
    },
    // 清空购物车
    setCartEmpty: function (state) {
      MessageBox.confirm('清空购物车?', '').then(action => {
        state.foodsInCart.forEach((food) => {
          Vue.set(food, 'count', 0);
        });
        state.foodsInCart = [];
      });
    },
    // 静默清空购物车，不询问
    setCartEmptySilent: function (state) {
      state.foodsInCart.forEach((food) => {
        Vue.set(food, 'count', 0);
      });
      state.foodsInCart = [];
    },
   /* getUserInfo: function (state) {
      getUserInfoByUserId().then(data => {
        state.userInfo = data;
      });
    }, */
    getAllCardsList: function (state) {
      getUsercardList().then(data => {
        state.allCardsList = data;
      });
    },
    /* getSysPointsConfig: function (state) {
      getPointsConfig().then(data => {
        state.pointsConfig = data;
      });
    }, */
    getLocalFoodsInCart: function (state) {
      let _tempFoodsInCart = getSessionStorageItem('foodsInCart');
      if (_tempFoodsInCart !== null && _tempFoodsInCart.length > 0) {
        state.localFoodsInCart = _tempFoodsInCart;
      }
    },
    setRemoteBusinessSetting: function (state) {
      getBusinessSetting().then(res => {
      });
    },
    getRemoteBusinessSetting: function (state) {
      let _tempBusinessSetting = getSessionStorageItem('businessSetting');
      if (_tempBusinessSetting !== null && _tempBusinessSetting.length > 0) {
        console.log(_tempBusinessSetting);
        state.businessSettingInfo = _tempBusinessSetting;
        return state.businessSettingInfo;
      }
    },
    setTotalPrice: function (state, totalPrice) {
      state.totalPrice = totalPrice;
      return state.totalPrice;
    },
    setCardsInfo: function (state, card) {
      state.selectedCard = card;
      return state.selectedCard;
    },
    setTheSameFood: function (state, isTheSAMEFOOD) {
      state.theSameFood = isTheSAMEFOOD;
    },
    setArriveTime: function (state, arriveTime) {
      state.arriveTime = arriveTime;
    },
    setPersonNum: function (state, personNum) {
      state.personNum = personNum;
    }
  },
  actions: {
    // 多个菜品批量加入购物车（再来一单）
    addOrderFoodsToCart ({commit}, foods) {
      if (foods.length > 0) {
        for (let orderFood of foods) {
          commit('addFoodsToCart', orderFood);
        }
      }
    }
  }
});
